import { ContactType } from "@/constants/ContactType";
import { contacts_mgr, ISessionItem, sessions_mgr } from "@/mgr";
import { useEffect, useMemo } from "react";
import { useImmer } from "use-immer";

interface IState {
  list: ISessionItem[];
  loading?: boolean;
  error?: any;
}
const init_data: IState = { list: [] };
interface IOpts {
  keys?: string;
  contact_types?: ContactType.Value[];
  keyword?: string;
}
const state_map: { [x in string]?: IState } = {}

export function useWXSessions(opts: IOpts = {}) {
  const { keys } = opts;

  const [state, set_state] = useImmer<IState>((keys ? state_map[keys] : 0) || init_data);
  if (keys) state_map[keys] = state
  const { contact_types, keyword } = opts;
  const { list, loading } = state

  const _list = useMemo(() => list.filter(item => {
    // 观察到无消息时，该值为0，可能是点开了联系人，但未发送消息，过滤之
    if (!item.nOrder) return false;

    // 类型过滤
    if (
      contact_types?.length &&
      !contact_types.some(b => b === item.contact_type)
    ) return false;

    // 关键字过滤
    const kw = keyword?.trim()
    if (!kw) return true
    if (item.userName.indexOf(kw) >= 0) return true;
    if (item.content.indexOf(kw) >= 0) return true;
    if (item.nTime.indexOf(kw) >= 0) return true;
    if (item.nickName.indexOf(kw) >= 0) return true;
    if (item.contact_type_name.indexOf(kw) >= 0) return true;

    const contact = contacts_mgr.map.get(item.userName)
    if (!contact) return false;
    if (contact.alias.indexOf(kw) >= 0) return true;
    if (contact.remark.indexOf(kw) >= 0) return true;
    return false

  }), [contact_types, list, keyword])

  useEffect(() => {
    set_state({
      list: sessions_mgr().list,
      error: sessions_mgr().error,
      loading: sessions_mgr().loading
    });
    let tid: ReturnType<typeof setTimeout> | null = null;
    const clear_callbacks = sessions_mgr().callbacks.add({
      on_loading_changed(mgr, is_loading) {
        if (tid) clearTimeout(tid)
        tid = setTimeout(() => {
          set_state(o => { o.loading = is_loading });
          tid = null;
        }, 1000)
      },
      on_list_change(mgr) {
        set_state(o => {
          o.list = mgr.list
          o.error = mgr.error
        });
      },
    });
    return () => {
      clear_callbacks()
      if (tid) clearTimeout(tid)
    };
  }, [sessions_mgr]);

  return { sessions: _list, loading }
}
